const Service = require('egg').Service;



/**
 * 接口管理
 */
class ApiService extends Service {
	tableName = 'mock-api';
	// 接口查询
	async queryApi(id) {
		const { ctx, app, service } = this;
		/**
		 * 1. 根据分类id查找当前分类下的所有接口信息
		 * 2. 根据分类所属的表，把相关接口数据存入到对应的表中
		 */
		// const _id = app.getObjectId(id);
		// 2.根据分类表查找接口
		const res = await app.mongo.find(this.tableName, {
			query: { categoryId: id }
		})
		return res;
	}
	async getCategoryTable(_id) {
		const { app } = this;
		// 查找分类信息
		const category = await app.mongo.findOne('mock-api-category', {
			query: { _id }
		});
		if(category == null) throw new HttpException(401,'没有当前分类')
		// 根据分类信息中的  parentId 从mock-server-table 找到分类对应的表名称
		const table = await app.mongo.findOne('mock-server-table', {
			query: { _id: app.getObjectId(category.parentId) }
		})
		if(table == null) throw new HttpException(401,'没有分类对应表')
		return { ...table, ...category };
	}
	// 创建接口分类
	async createApi(data) {
		const { ctx, app } = this;
		const createTime = ctx.helper.getCurrentTime();
		const _id = app.getObjectId(data.categoryId);
		// // 找到分类下对应的表信息
		const table = await this.getCategoryTable(_id);
		// 从对应的表中插入数据
		const res = await app.mongo.insertOne(this.tableName, {
			doc: { createTime, ...data, tableName: table.name, categoryName: table.categoryName }
		});
		return res;
	}
	// 更新接口
    async updateApi(data) {
        const { ctx, app } = this;
        const _id = app.getObjectId(data._id);
        const { apiName, apiPath, apiType, desc  } = data;
        const res = await app.mongo.findOneAndUpdate(this.tableName, {
            filter: { _id },
            update: {
                $set: { apiName, apiPath, apiType, desc }
            }
        });
		return res;
    }
	// 删除接口
	async deleteApi(id) {
		const { ctx, app } = this;
		const _id = app.getObjectId(id);
		// const category = app.mongo.findOne(this.tableName, {
		// 	query: { _id }
		// })
		// if (category === null) {
		// 	throw new HttpException(401, '没有当前分类表')
		// }
		const res = await app.mongo.findOneAndDelete(this.tableName, {
			filter: { _id }
		});
		return res;
	}
}

module.exports = ApiService;
